package com.tebiecloud.mpweixin.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.security.SecurityHelper;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinReceiveMggLog;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUserExpand;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUserWallet;
import com.tebiecloud.mpweixin.server.service.MpweixinMggFlowService;
import com.tebiecloud.mpweixin.server.service.MpweixinReceiveMggLogService;
import com.tebiecloud.common.model.PageParams;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.ResultBodyUtils;
import com.tebiecloud.mpweixin.server.service.MpweixinUserExpandService;
import com.tebiecloud.mpweixin.server.service.MpweixinUserWalletService;
import com.tebiecloud.mpweixin.server.service.feign.OrderGoodsServiceClient;
import com.tebiecloud.mpweixin.server.service.feign.OrderServiceClient;
import com.tebiecloud.order.client.model.entity.OrderEvaluate;
import com.tebiecloud.order.client.model.entity.OrderGoods;
import com.tebiecloud.order.client.model.entity.Orderr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 *  前端控制器
 * @author tebie
 * @date 2019-10-30
 */
@RestController
@RequestMapping("/mpweixinreceivemgglog")
public class MpweixinReceiveMggLogController {

    @Autowired
    private MpweixinReceiveMggLogService mpweixinReceiveMggLogService;

    @Autowired
    private MpweixinUserWalletService mpweixinUserWalletService;

    @Autowired
    private MpweixinMggFlowService mpweixinMggFlowService;

    @Autowired
    private MpweixinUserExpandService mpweixinUserExpandService;

    @Autowired
    private OrderServiceClient orderServiceClient;

    @Autowired
    private OrderGoodsServiceClient orderGoodsServiceClient;

    /**
     * 领取乖乖币
     * @param sourceUserId 分享人id,
     * @param coin 领取的乖乖币
     * @return
     */
    @PostMapping("add")
    public ResultBody add(
            @RequestParam(value = "sourceUserId", required = false) Long sourceUserId,
            @RequestParam(value = "orderId", required = false) Long orderId,
            @RequestParam(value = "coin", required = false) Integer coin) {
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long userId = securityUserDetails.getUserId();
        //先查询是否领取过
        QueryWrapper<MpweixinReceiveMggLog> mpweixinReceiveMggLogQueryWrapper = new QueryWrapper<>();
        mpweixinReceiveMggLogQueryWrapper.eq("order_id",orderId);
        mpweixinReceiveMggLogQueryWrapper.eq("receive_user_id",userId);
        mpweixinReceiveMggLogQueryWrapper.last("LIMIT 1");
        MpweixinReceiveMggLog mpweixinReceiveMggLogOld = mpweixinReceiveMggLogService.getOne(mpweixinReceiveMggLogQueryWrapper);
        if(mpweixinReceiveMggLogOld!=null){
            return ResultBodyUtils.failedMsg("该用户已经领取过了");
        }
        //如果是评价后领取，查询评价获取乖币
        if(coin==null){
            ResultBody<OrderEvaluate> orderEvaluateResultBody = orderServiceClient.selectOrderEvaluate(orderId);
            if(orderEvaluateResultBody!=null && orderEvaluateResultBody.getCode() == ResultEnum.OK.getCode()){
                OrderEvaluate orderEvaluate = orderEvaluateResultBody.getData();
                if(orderEvaluate!=null){
                    coin = orderEvaluate.getCoin();
                }else {
                    coin = 0;
                }
            }
        }
        MpweixinReceiveMggLog mpweixinReceiveMggLog = new MpweixinReceiveMggLog();
        mpweixinReceiveMggLog.setReceiveUserId(userId);
        mpweixinReceiveMggLog.setOrderId(orderId);
        mpweixinReceiveMggLog.setReceiver(securityUserDetails.getNickName());
        mpweixinReceiveMggLog.setReceiverHeadimgurl(securityUserDetails.getAvatar());
        mpweixinReceiveMggLog.setSourceUserId(sourceUserId);
        mpweixinReceiveMggLog.setCoin(coin);
        if(mpweixinReceiveMggLogService.save(mpweixinReceiveMggLog)){
            if(coin>0){
                //添加乖乖币到账
                mpweixinUserWalletService.updatePlusAmount(userId,0,coin);
                //添加记录
                mpweixinMggFlowService.saveCoinFlow(userId,orderId,coin,6);
            }
        }
        QueryWrapper<MpweixinUserWallet> mpweixinUserWalletQueryWrapper = new QueryWrapper<>();
        mpweixinUserWalletQueryWrapper.eq("user_id",userId);
        mpweixinUserWalletQueryWrapper.last("LIMIT 1");
        MpweixinUserWallet mpweixinUserWallet = mpweixinUserWalletService.getOne(mpweixinUserWalletQueryWrapper);
        Map<String,Object> resultMap = Maps.newHashMap();
        resultMap.put("currentCoin",mpweixinUserWallet.getMgg());//目前总乖乖币
        resultMap.put("coin",coin);//领取的乖乖币
        return ResultBodyUtils.ok(resultMap);
    }

    /**
     * 获取领取
     * @param orderId
     * @return
     */
    @PostMapping("get")
    public ResultBody get(
            @RequestParam(value = "orderId", required = false) Long orderId,
            @RequestParam(value = "sourceUserId", required = false) Long sourceUserId) {
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long userId = securityUserDetails.getUserId();
        QueryWrapper<MpweixinReceiveMggLog> mpweixinReceiveMggLogQueryWrapper = new QueryWrapper<>();
        mpweixinReceiveMggLogQueryWrapper.eq("order_id",orderId);
        mpweixinReceiveMggLogQueryWrapper.eq("receive_user_id",userId);
        mpweixinReceiveMggLogQueryWrapper.last("LIMIT 1");
        MpweixinReceiveMggLog mpweixinReceiveMggLogOld = mpweixinReceiveMggLogService.getOne(mpweixinReceiveMggLogQueryWrapper);
        Map<String,Object> resultMap = Maps.newHashMap();
        int isMyShare = 0;//默认不是我的
        int isReceive = 0;//默认没有领取
        //查询订单信息
        ResultBody<Orderr> orderrResultBody = orderServiceClient.selectOrder(orderId);
        if(orderrResultBody!=null && orderrResultBody.getCode() == ResultEnum.OK.getCode()){
            Orderr orderr = orderrResultBody.getData();
            if(orderr!=null){
                //判断是不是自己分享出去的
                if(orderr.getUserId()!=null && orderr.getUserId() == userId){
                    isMyShare = 1;
                }
            }
        }
        if(mpweixinReceiveMggLogOld!=null){
            QueryWrapper<MpweixinUserWallet> mpweixinUserWalletQueryWrapper = new QueryWrapper<>();
            mpweixinUserWalletQueryWrapper.eq("user_id",userId);
            mpweixinUserWalletQueryWrapper.last("LIMIT 1");
            MpweixinUserWallet mpweixinUserWallet = mpweixinUserWalletService.getOne(mpweixinUserWalletQueryWrapper);
            int currentCoin = 0;
            if(mpweixinUserWallet!=null)currentCoin = mpweixinUserWallet.getMgg()==null?0:mpweixinUserWallet.getMgg();
            resultMap.put("isReceive",1);//是否领取过：0否，1是
            isReceive = 1;
            resultMap.put("currentCoin",currentCoin);//目前总乖乖币
            resultMap.put("coin",mpweixinReceiveMggLogOld.getCoin()==null?0:mpweixinReceiveMggLogOld.getCoin());//领取的乖乖币
        }else{
            resultMap.put("isReceive",0);//是否领取过：0否，1是
            resultMap.put("currentCoin",0);//目前总乖乖币
            resultMap.put("coin",0);//领取的乖乖币
        }
        //查询分享人
        if(sourceUserId!=null){
            QueryWrapper<MpweixinUserExpand> mpweixinUserExpandQueryWrapper = new QueryWrapper<>();
            mpweixinUserExpandQueryWrapper.eq("user_id",sourceUserId);
            MpweixinUserExpand mpweixinUserExpand = mpweixinUserExpandService.getOne(mpweixinUserExpandQueryWrapper);
            if(mpweixinUserExpand!=null){
                resultMap.put("userName",mpweixinUserExpand.getNickname());
            }
        }else {
            resultMap.put("userName","");
        }
        if(isMyShare==1 && isReceive==0){
            //查询订单数据
            ResultBody<List<OrderGoods>> listResultBody = orderGoodsServiceClient.listOrderGoods(orderId);
            if(listResultBody!=null && listResultBody.getCode()== ResultEnum.OK.getCode()){
                List<OrderGoods> orderGoodsList = listResultBody.getData();
                int coin = 0;
                if(orderGoodsList!=null && orderGoodsList.size()>0){
                    for(OrderGoods orderGoods:orderGoodsList){
                        coin = coin + orderGoods.getCoin();
                    }
                }
                resultMap.put("coin",coin);//需要领取的乖乖币
            }
        }
        resultMap.put("isMyShare",isMyShare);
        return ResultBodyUtils.ok(resultMap);
    }

//    /**
//     * 获取分页数据
//     * @param map
//     * @return
//     */
//    @GetMapping(value = "list")
//    public ResultBody<IPage<MpweixinReceiveMggLog>> list(@RequestParam(required = false) Map map) {
//        PageParams pageParams = new PageParams(map);
//        MpweixinReceiveMggLog query = pageParams.mapToObject(MpweixinReceiveMggLog.class);
//        QueryWrapper<MpweixinReceiveMggLog> queryWrapper = new QueryWrapper();
//        return ResultBodyUtils.ok(mpweixinReceiveMggLogService.page(new PageParams(map), queryWrapper));
//    }
//
//    /**
//     * 更新数据
//     * @param receiveUserId 领取人id
//     * @param receiver 领取人昵称
//     * @param receiverHeadimgurl 领取人头像
//     * @param sourceUserId 分享人id
//     * @param coin 领取的乖乖币
//     * @return
//     */
//    @PostMapping("update")
//    public ResultBody update(
//            @RequestParam(value = "receiveMggId", required = false) Long receiveMggId,
//            @RequestParam(value = "receiveUserId", required = false) Long receiveUserId,
//            @RequestParam(value = "receiver", required = false) String receiver,
//            @RequestParam(value = "receiverHeadimgurl", required = false) String receiverHeadimgurl,
//            @RequestParam(value = "sourceUserId", required = false) Long sourceUserId,
//            @RequestParam(value = "coin", required = false) Integer coin
//    ) {
//        MpweixinReceiveMggLog entity = new MpweixinReceiveMggLog();
//        entity.setReceiveMggId(receiveMggId);
//        entity.setReceiveUserId(receiveUserId);
//        entity.setReceiver(receiver);
//        entity.setReceiverHeadimgurl(receiverHeadimgurl);
//        entity.setSourceUserId(sourceUserId);
//        entity.setCoin(coin);
//        mpweixinReceiveMggLogService.updateById(entity);
//        return ResultBodyUtils.ok();
//    }
//
//    /**
//     * 删除数据
//     * @param id 单个id
//     * @param ids 多个id用,号隔开
//     * @return
//     */
//    @PostMapping("remove")
//    public ResultBody remove(
//            @RequestParam(value = "id", required = false) Long id,
//            @RequestParam(value = "ids", required = false) String ids
//    ) {
//        if(id != null && id > 0) {
//            mpweixinReceiveMggLogService.removeById(id);
//        }
//        if(ids != null && ids.length() > 0) {
//            mpweixinReceiveMggLogService.removeByIds(Arrays.asList(ids.split(",")));
//        }
//        return ResultBodyUtils.ok();
//    }

}
